package com.ubxtech.gateway.config;

import com.ubxtech.gateway.balance.GrayLoadBalancerRule;
import com.ubxtech.gateway.balance.VersionGrayLoadBalancerRule;
import com.ubxtech.gateway.filter.GrayReactiveLoadBalancerFilter;
import com.ubxtech.gateway.properties.CustomGatewayProperties;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.gateway.config.GatewayLoadBalancerProperties;
import org.springframework.cloud.gateway.config.GatewayReactiveLoadBalancerClientAutoConfiguration;
import org.springframework.cloud.gateway.filter.ReactiveLoadBalancerClientFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 灰度发布配置
 * @author Victor.Xiao
 * @since 2023-08-18 18:17
 **/
@Configuration
@EnableConfigurationProperties({CustomGatewayProperties.class,GatewayLoadBalancerProperties.class})
@ConditionalOnProperty(value = "ubxtech.gateway.grayFlag", havingValue = "1",matchIfMissing = true)
@AutoConfigureBefore(GatewayReactiveLoadBalancerClientAutoConfiguration.class)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
public class GrayGatewayConfig {

    @Bean
    public ReactiveLoadBalancerClientFilter gatewayLoadBalancerClientFilter(GrayLoadBalancerRule grayLoadBalancerRule,
                                                                            GatewayLoadBalancerProperties properties) {
        return new GrayReactiveLoadBalancerFilter(properties, grayLoadBalancerRule);
    }

    @Bean
    public GrayLoadBalancerRule grayLoadBalancer(DiscoveryClient discoveryClient,CustomGatewayProperties customGatewayProperties) {
        return new VersionGrayLoadBalancerRule(discoveryClient,customGatewayProperties);
    }
}
